//
//  KouDaiViewController.m
//  MyProject
//
//  Created by apple on 15/11/3.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "KouDaiViewController.h"
#import "AFNetworking.h"
#import "KouDaiModel.h"
#import "JSONModelArray.h"
#import "UIImageView+AFNetworking.h"
#import "JHRefresh.h"
#import "MMProgressHUD.h"
#import "LZXHelper.h"
#import "NSString+Hashing.h"
#import "KouDaiCellPushViewController.h"
#define URL (@"http://chanyouji.com/api/destinations/attractions/%@.json?")
@interface KouDaiViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    NSMutableArray *_dataArr;
}

@property (nonatomic,assign)NSInteger page;
@property (nonatomic,strong)UITableView *tableView;
@end

@implementation KouDaiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _page = 1;
    
    _dataArr = [[NSMutableArray alloc]initWithCapacity:0];
    
    [self getData];
    [self createView];
    [self createNavigationBar:9];
    self.back.text = @"风景";
    
}

-(void)getData
{
    
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleDrop];
    //显示 特效 设置 标题
    [MMProgressHUD showWithTitle:@"下载" status:@"Loading..."];

    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:[NSString stringWithFormat:URL,self.ID] parameters:@{@"per_page":@"20",@"page":@(self.page)} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //NSLog(@"%@",responseObject);
        //数据解析  睡一波。。。
        
        if (self.page == 1) {
            [_dataArr removeAllObjects];
        }
        
        NSArray * arr = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        for (NSDictionary * dic in arr) {
            KouDaiModel * model = [[KouDaiModel alloc]initWithDictionary:dic error:nil];
            if (!model) {
                continue;
            }
            [_dataArr addObject:model];
        }
        [_tableView reloadData];
        //下载完成之后 把数据 保存本地沙盒中(缓存)
        //直接把下载的二进制数据  responseObject写入本地文件
        NSString *path = [LZXHelper getFullPathWithFile:[NSString  stringWithFormat:URL,self.ID]];
        //写文件
        NSData *data = (NSData *)responseObject;
        //每一页 都做 缓存
        [data writeToFile:path atomically:YES];
        [MMProgressHUD dismissWithSuccess:@"下载完成" title:@"ok"];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}


-(void)createView
{
    _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:0];
    [self.view addSubview:_tableView ];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    //注册cell
    [_tableView registerNib:[UINib nibWithNibName:@"KouDaiCell" bundle:nil] forCellReuseIdentifier:@"234"];
    
    //刷新
    __weak typeof(self)weakSelf = self;
    [_tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        weakSelf.page = 1;
        [weakSelf getData];
        [weakSelf.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess];
    }];
    
    [_tableView addRefreshFooterViewWithAniViewClass:[JHRefreshAmazingAniView class] beginRefresh:^{
        weakSelf.page ++;
        [weakSelf getData];
        [weakSelf.tableView footerEndRefreshing];
    }];
    
    
    
}

#pragma mark - 代理方法 － 
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   
    return _dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KouDaiModel *model = [_dataArr objectAtIndex:indexPath.row];
    
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"234"];
    UIImageView *imgV = (UIImageView *)[cell.contentView viewWithTag:1000];
    [imgV setImageWithURL:[NSURL URLWithString:model.image_url]];
    UILabel *labke1 = (UILabel *)[cell.contentView viewWithTag:1001];
    labke1.text = model.name;
    
    UILabel *labke2 = (UILabel *)[cell.contentView viewWithTag:1002];
    labke2.text = [NSString stringWithFormat:@"%ld",model.attraction_trips_count];
    
    UILabel *labke3 = (UILabel *)[cell.contentView viewWithTag:1003];
    labke3.text = [NSString stringWithFormat:@"%@/5.0",model.user_score];
    
    UILabel *labke4 = (UILabel *)[cell.contentView viewWithTag:1004];
    labke4.text = model.desc;
    
    
    
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
    
}
//点击了某个cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    KouDaiCellPushViewController * push = [[KouDaiCellPushViewController alloc]init];
    
    KouDaiModel * model = [_dataArr objectAtIndex:indexPath.row];
    push.ID = model.id;
    push.headName = model.name;
    [self.navigationController pushViewController:push animated:YES];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
